package se.statifyme.client.declaration;

import se.thoka.twt.client.form.TWTForm;
import se.thoka.twt.client.form.TWTFormField;
import se.thoka.twt.client.form.TWTFormFieldRenderer;
import se.thoka.twt.client.form.TWTFormRenderer;
import se.thoka.twt.client.json.TWTJSONParser;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class DeclaredItemForm extends Composite {

	interface Binder extends UiBinder<Widget, DeclaredItemForm> {
	}

	@UiField
	HasText itemName;

	@UiField
	HasWidgets fieldsContainer;

	private TWTForm form;

	public DeclaredItemForm() {
		initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this));
	}

	public void setDeclaredItem(GWTItemDeclaration itemDeclaration) {
		form = new TWTForm();
		itemName.setText(itemDeclaration.getDisplayName());
		fieldsContainer.clear();
		for (GWTItemFieldDeclaration field : itemDeclaration.getFields()) {
			TWTFormField<?> formField = FieldUtil.createFieldForType(field);
			form.add(formField);
			formField.setEnabled(!field.isInternal());
			TWTFormRenderer formRenderer = TWTFormRenderer.getInstance();
			TWTFormFieldRenderer fieldRenderer = formRenderer.getRenderer(formField);
			fieldsContainer.add(fieldRenderer.render(formField, true));
		}
	}

	public void setJSONItemDeclaration(JSONValue value) {
		GWTItemDeclaration declaration = TWTJSONParser.parseObject(GWTItemDeclaration.class, value);
		setDeclaredItem(declaration);
	}

}
